<?php
namespace Popshouse\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller as Control;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\SecurityContext;

use Popshouse\AdminBundle\Model\Translation;
use Popshouse\AdminBundle\Form\TranslationForm;

class TranslationController extends Control
{
    /**
     * @extra:Template()
     */
    public function indexAction()
    {
        return array('domains' => Translation::listAll(true), 'active' => 'trans');
    }

    /**
     * @extra:Template()
     */
    public function domainAction($domain){
    
    	$translation = new Translation($domain);
    	$translation->load();

    	return array('translation'=>$translation,'domain'=>$domain, 'active' => 'trans');
    }
    
    public function saveAction($domain){
    	$translation = new Translation($domain);
    	$request = $this->get('request');
    	$strings = $request->request->get('strings');
    	foreach($strings as $string){
    		foreach($translation->getLangs() as $lang){
    			if(!empty($string['key']))
    				$translation->set($string['key'],$lang,$string[$lang]);
    		}
    	}
    	$translation->save();
    	$this->get('session')->setFlash('notice', 'Categorie "'.$domain.'" opgeslaan');
        return new RedirectResponse($this->generateUrl('trans'));
    	//die(print_r($request->request->get('strings'),true));
    }
    

    /**
     * @extra:Template()
     */
    public function createAction(){

    	$form = $this->get('form.factory')->createNamed(new TranslationForm(),'translation');
        $request = $this->get('request');
	    if ($request->getMethod() == 'POST') {
	        $form->bindRequest($request);
	        if ($form->isValid()) {
	        	$domain = $request->request->get('translation');
	        	$domain = $domain['naam'];
	   			$translation = new Translation($domain);
	    		$translation->save();
	    		
		        $this->get('session')->setFlash('notice', 'Categorie "'.$domain.'" aangemaakt');
	           	return new RedirectResponse($this->generateUrl('trans'));
	        }
	    }

        return array('form' => $form->createView(), 'active' => 'trans');
    	
    }
    
    public function deleteAction($domain){
    	$translation = new Translation($domain);
    	$translation->delete();
    	  return new Response(json_encode(array('message'=>'Verwijdert')));
    }

}
